<?php
define('fake_prefix', 'fake_');
class webPage {
	//TODO::uniUser相关信息暂时没有处理
	/*
	 * http://localhost/weixin/call.json?userName=fromuser&customerId=1&module=webPage&method=getWebPage&params={%22id%22:1}
	*/
	//根据模版id获取模版详细信息
	public static function getTemplateById($tplid){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);		
		$WebPageModel = M("pb_template");
		$where['id'] = array('eq',$tplid);
		$res = $WebPageModel -> where($where)->find();
		Session::switchCustomer($customerId);
		return $res;		
	}
	
	public static function getWebPageById($id, $userName, $srcUserName){		
		$WebPageModel = M("web_page");
		$result = $WebPageModel->where("id=$id")->find();
		if (!$result) {
			Output::instance()->resultCode(code_webpage_not_exist);
			return;
		}
		
		if ($result["readAccess"] == 2) {
			$access = self::readAccess($userName);
			if (!$access) {
				return;
			}
		}
		
        $readCount = intVal($result['readCount']) + 1;
//        if($result['createTime'] == null){
//            $result['createTime'] = $dataCount['createTime'] = date('Y-m-d H:i:s');
//        }
        $result['readCount'] = $readCount;
//        $cid = Session::$user['customerId'];
//        $cuModel = M('customer_user','wx_');
//        $focusName = $cuModel->where(" `customerId` = {$cid}")->getfield('fullName');
//        $result['focusName'] = $focusName;
        $dataCount['readCount'] = $readCount;
        $WebPageModel->where("id=$id")->save($dataCount);

		$tplid = isset($result["tplid"]) ? $result["tplid"] : 1;
		$templatename = webPage::getTemplateById($tplid);
		$templatename = $templatename ==''?'webpage' : $templatename['htmlname'];
		
		$AttachmentModel = M("web_page_attachment");
		$attchement = $AttachmentModel->where("webPageId=$id")->select();
		if ($attchement) {
			$result["attachments"] = $attchement;
		}
			
		$comment = get_comment_and_rate_by_moduleId($id, 'webPage', $userName);
		if ($comment) {
			$result["commentCount"] = $comment["commentCount"];
			if ($comment["commentCount"] != 0) {
				$result["comments"] = $comment["comments"];
			}
			$result["rateCount"] = $comment["rateCount"];
		//	$result["alreadyComment"] = $comment["alreadyComment"];
			$result["alreadyRate"] = $comment["alreadyRate"];
		} else {
			$result["alreadyComment"] = 0;
			$result["alreadyRate"] = 0;
		}
		
		if ($userName != '') {
			set_point_by_point_type(module_handle_browseWebpage, $userName,false,$result['title']);
				
			$userInfo = get_UserInfo_by_fromUserName($userName);
			if ($userInfo) {
				$result["fullName"] = $userInfo[user_full_name];
			}
		} else {
			// no username can not comment rate
			$result["alreadyComment"] = 1;
			$result["alreadyRate"] = 1;
		}
		// repost
		$event = self::getWebPageEvent($id);
		if ($event) {
			if ($srcUserName != NULL) {
				self::repostWebPage($id, $event, $srcUserName, $userName);
			} else if ($userName != '') {
				$result["repostCount"] = self::getRepostCount($id, $userName);
			}
		}
		//ihziluoh 添加标签
		if(!empty($result['accessTag']) && !empty($userName)){	
			setAccessTags($result['accessTag'],$userName,module_handle_webPage, $id);
		}
		//ihziluoh 添加标签
		//
		$result['focusLink'] = ($result['focusLink'] === '') ? "javascript:void(0)" : $result['focusLink'];

		Output::instance()->module('webPage', $templatename)->object($result);
	
	}
	
	private static function readAccess($userName) {
		if ($userName == '') {
			Output::instance()->resultCode(code_user_not_member);
			return false;
		}
		
		$isMember = R("Member/verifyMember");
		switch ($isMember){
			case -1:
				Output::instance()->resultCode(code_user_not_member);
				return false;
			case 0:
				Output::instance()->resultCode(code_user_member_not_check);
				return false;
			case 1://审核通过
				return true;
			case 2:
				Output::instance()->resultCode(code_user_member_is_checking);
				return false;
			default:
				Output::instance()->resultCode(code_user_not_member);
				return false;
		}
	}
	
	public static function repostWebPage($webPageId, $event, $srcUserName, $userName) {
		if ($userName == '') {
			$uniUserId = getFakeOpenId();
		} else {
			$uniUser = get_UniUser_by_userName($userName);
			if($uniUser){
				$uniUserId = $uniUser['uniUserId'];
			}else{
				$uniUserId = create_UniUser_by_userName($userName);
			}
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$RepostModel = M("web_page_repost_view");
		$data["fromCustomerId"] = $customerId;
		$data["webPageId"] = $webPageId;
		$data["srcFromUserName"] = $srcUserName;
		$data["uniUserId"] = $uniUserId;
		$data["eventId"] = $event["eventId"];
		$result = $RepostModel->where($data)->find();
		
		Session::switchCustomer($customerId);
		if (!$result) {
			$time = date("Y-m-d H:i:s");
			$data["createTime"] = $time;
			$result = $RepostModel->add($data);
		} else {
			return;
		}
		
		$point = $event["point"];
		if ($point != NULL && $point != 0) {
			set_point_by_fromUserName($srcUserName, module_handle_repostWebpage, false,$event['webPageTitle'], NULL, $event["eventId"], $point);
		}
	}
	
	public static function getWebPageEvent($webPageId) {
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$time = date("Y-m-d H:i:s");
		$EventModel = M("web_page_event");
		$where["pevent.fromCustomerId"] = $customerId;
		$where["pevent.webPageId"] = $webPageId;
		$where["pevent.eventType"] = REPOST_TYPE_WEBPAGE;
		$where["pevent.deleted"] = 0;
		$where["event.startTime"] = array(array('exp', 'IS NULL'), array('elt', $time), 'or');
		$where["event.endTime"] = array(array('exp', 'IS NULL'), array('egt', $time), 'or');
		$where["event.deleted"] = 0;
		$event = $EventModel->alias("pevent")->join("wx_event event ON event.id = pevent.eventId")->where($where)->find();
		
		Session::switchCustomer($customerId);
		return $event;
	}
	
	public static function getRepostCount($webPageId, $userName) {
		if ($userName == '') {
			return 0;
		}
		$uniUser = get_UniUser_by_userName($userName);
		if($uniUser){
			$uniUserId = $uniUser['uniUserId'];
		}else{
			$uniUserId = create_UniUser_by_userName($userName);
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		
		$RepostModel = M("web_page_repost_view");
		$data["fromCustomerId"] = $customerId;
		$data["webPageId"] = $webPageId;
		$data["srcUniUserId"] = $uniUserId;
		$count = $RepostModel->where($data)->count();
		Session::switchCustomer($customerId);
		return $count;
	}
	
	//根据标签模板id获取详细信息
	private static function getTagTemplateById($tplid){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$tagModel = M("webpage_tag_template");
		Session::switchCustomer($customerId);
		$where["id"] = $tplid;
		$tagTpl = $tagModel->where($where)->find();
		return $tagTpl;
	}
	
	public static function getWebPageTag($field, $value, $start, $limit,$tplid) {
		$TagModel = M("web_page_tag");
		if($field == 'tagName'){
			$tag = $TagModel->field("tagName,picUrl,description")->where("$field='$value'")->find();
			$tagName = $value;
		}else if($field == 'id'){
			$tag = $TagModel->field("tagName,picUrl,description")->where("$field='$value'")->find();
			$tagName = $tag["tagName"];
		}
	
	
		$sql = $TagModel->field("id")->where("$field='$value'")->select(false);
		$condition["_string"] = "tagId in ($sql)";
		$TagListModel = M("web_page_tag_list");
		$sql = $TagListModel->field("webPageId")->where($condition)->select(false);
		$where["_string"] = "id IN ($sql)";
		$where["deleted"] = 0;
		$WebPageModel = M("web_page");
		$arr = $WebPageModel->where($where)->order("stickyPostTime desc, updateTime desc")->limit($start, $limit)->select();
		//echo $WebPageModel->getLastSql();
		if ($arr) {
			for($i = 0; $i < count($arr); $i++) {
				if ($arr[$i]["comment"] == "1" || $arr[$i]["rate"] == "1") {
	
					$obj = get_comment_and_rate_obj_by_moduleId($arr[$i]["id"], "webPage");
					if ($obj) {
						// "0" won't show in page
						$arr[$i]["commentCount"] = $obj["commentCount"] == "0" ? " 0" : $obj["commentCount"];
						$arr[$i]["rateCount"] = $obj["rateCount"] == "0"? " 0" : $obj["rateCount"] ;
					} else {
						$arr[$i]["commentCount"] = " 0";
						$arr[$i]["rateCount"] = " 0";
					}
				}
				if($i == 0){
					$arr[$i]["tagName"] = $tagName;
					$arr[$i]["picUrl"] = $tag['picUrl'];
					$arr[$i]["description"] = $tag['description'];
				}
			}
			
			$tagTpl = webPage:: getTagTemplateById($tplid);
			if (!$tagTpl) {
				Output::instance()->resultCode(code_custom_error);
				return;
			}
			$htmlname = $tagTpl["htmlname"];
			Output::instance()->module('webPage', $htmlname)->objArray($arr,  $WebPageModel->where($where)->count());
		} else {
			Output::instance()->resultCode(code_success);
		}
	}
	
}